/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: RxResponse
 * @Package com.rx.core.base
 * @Description: 返回报文
 * @author: 陈锦韬
 * @date: 2020\4\19 0019
 * @version V1.0
 * @Copyright: 2020 陈锦韬  All rights reserved.
 */
package com.rx.core.base;

import com.alibaba.fastjson.JSON;
import com.rx.core.enm.RESULT_CODE;
import com.rx.core.util.EmptyChecker;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: Administrator
 * @Description: 返回报文
 * @date: 2020\4\19 0019
 */
@Data
@EqualsAndHashCode(callSuper=false)
public class RxResponse extends RxBaseData {
    private static final long serialVersionUID = 1L;

    private String resultCode= RESULT_CODE.OK.getCode();

    private String resultMessage= RESULT_CODE.OK.getDesc();

    private Object resultData;

    public RxResponse(String resultCode, String resultMessage) {
        this.resultCode = resultCode;
        this.resultMessage = resultMessage;
    }
    public RxResponse() {
        this.resultCode = RESULT_CODE.OK.getCode();
        this.resultMessage = RESULT_CODE.OK.getDesc();
    }
    public RxResponse(RxBaseException exception) {
        this.resultCode = exception.getResultCode();
        this.resultMessage = exception.getResultMessage();
    }
    public RxResponse(RxResultCode code) {
        this.resultCode = code.getCode();
        this.resultMessage = code.getDesc();
    }

    public RxResponse(RxResultCode code, final String ...object) {
        this.resultCode = code.getCode();
        if (EmptyChecker.notEmpty(object)){
            if (code.getDesc().contains("%s")){
                this.resultMessage = String.format(code.getDesc(),object);
            }else {
                this.resultMessage = String.format("%s",object);
            }

        }else {
            this.resultMessage = code.getDesc();
        }
    }

    public static RxResponse ok(){
        return new RxResponse();
    }

    public static RxResponse logout(){
        return new RxResponse(RESULT_CODE.LOG_OUT);
    }

    public static RxResponse fail(RxResultCode code){
        return new RxResponse(code);
    }

    public static RxResponse fail(RxResultCode code, String ...array){
        return new RxResponse(code,array);
    }

    public static void response(HttpServletResponse response,String message) throws IOException {
        // 无权限信息
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        RxResponse rxResponse = RxResponse.fail(RESULT_CODE.MESSAGE,message);
        out.append(JSON.toJSONString(rxResponse));
        out.close();
    }
}
